package com.df.gameserver.net.websocket.handler;

import com.df.MsgInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.util.List;

public class MsgToFrameHandler extends MessageToMessageEncoder<MsgInfo> {

    @Override
    protected void encode(ChannelHandlerContext ctx, MsgInfo msg, List<Object> out) throws Exception {
        BinaryWebSocketFrame frame = new BinaryWebSocketFrame();
        byte[] dataBytes = (byte[]) msg.getData();
        int dataLength = dataBytes.length;
        int allLength = dataLength + 4 + 4;

        ByteBuf content = frame.content();
        content.resetReaderIndex();
        content.resetWriterIndex();
        content.writeInt(allLength);
        content.writeInt(msg.getMsgId());
        content.writeBytes(dataBytes);
        out.add(frame);
    }


}
